//
//  FreightTemplateViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-22.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "FreightTemplateViewController.h"
#import "Config.h"
#import "Helper.h"
#import "JMFBase.h"
#import "AreaSelectViewController.h"

#define UNIT @"件"

//  -业务逻辑细节说明-
//
//  @abstract      

//  @discussion     1、在卖家承担运费时，运费相关的内容不用显示，同时也不用将相关参数传递给服务器
//                  2、由于区域运费是可选的，但还是有必要在用户在选择买家承担运费且没有设置区域运费的时候提醒用户。
//                  3、显示区域运费时，城市数最多像是5个。后面的城市计数是计算的二级城市的个数。

//  @notes          1、在设置显示区域运费列表的时候，一定要先将原来的列表清空，否则会出现相同的信息


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface FreightTemplateViewController ()

@end

@implementation FreightTemplateViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _templateContinueSaving = YES;
        
        _freightAreaSelected = [NSMutableArray new];
        
        _currentUnit = UNIT;
    }
    return self;
}

- (id)initWithTemplateId:(NSInteger)templateId
{
    self = [super init];
    if (self) {
        _templateId = templateId;
        
        _templateContinueSaving = YES;
        
        _freightAreaSelected = [NSMutableArray new];
        
        _currentUnit = UNIT;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //保存按钮
    UIButton *saveButton;
    if (_templateId == 0) {
        saveButton = [Helper buttonWithStyle:ButtonStyleNavigationDone];
    }
    else {
        
        saveButton = [Helper buttonWithStyle:ButtonStyleNavigationSave];
    }
    
    [saveButton addTarget:self action:@selector(saveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"freight_template" ofType:@"html"];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f)];
    _webView.delegate = self;

    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    if (_templateId == 0) {
        
        if ([[_webView stringByEvaluatingJavaScriptFromString:@"template_name.value"] length] == 0 &&
            [[_webView stringByEvaluatingJavaScriptFromString:@"check_freight_method();"] boolValue] &&
            [[_webView stringByEvaluatingJavaScriptFromString:@"default_quantity.value"] length] == 0 &&
            [[_webView stringByEvaluatingJavaScriptFromString:@"default_amount.value"] length] == 0 &&
            [[_webView stringByEvaluatingJavaScriptFromString:@"exceed_quantity.value"] length] == 0 &&
            [[_webView stringByEvaluatingJavaScriptFromString:@"exceed_amount.value"] length] == 0 &&
            _freightAreaSelected.count == 0 &&
            _sendReceivingId == 0 &&
            _returnReceivingId == 0
            ) {

            [self.navigationController dismissModalViewControllerAnimated:YES];
            
        }
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_109") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            [alertView show];
        }
        
    }
    else{

        if ([[_webView stringByEvaluatingJavaScriptFromString:@"template_name.value"] isEqualToString:_originalData[@"name"]] &&
            [[_webView stringByEvaluatingJavaScriptFromString:@"check_freight_method();"] boolValue] == ![_originalData[@"type"] boolValue] &&
            _sendReceivingId == [_originalData[@"sendReceivingId"] integerValue] &&
            _returnReceivingId == [_originalData[@"returnReceivingId"] integerValue]
            ) {
            
            //如果是买家承担运费就要判断以下选项
            if ([[_webView stringByEvaluatingJavaScriptFromString:@"check_freight_method();"] boolValue]) {
                
                if ([[_webView stringByEvaluatingJavaScriptFromString:@"default_quantity.value"] integerValue] == [_originalData[@"defaultQuantity"] integerValue] &&
                    [[_webView stringByEvaluatingJavaScriptFromString:@"default_amount.value"] integerValue] == [_originalData[@"defaultAmount"] integerValue] &&
                    [[_webView stringByEvaluatingJavaScriptFromString:@"exceed_quantity.value"] integerValue] == [_originalData[@"exceedQuantity"] integerValue] &&
                    [[_webView stringByEvaluatingJavaScriptFromString:@"exceed_amount.value"] integerValue] == [_originalData[@"exceedAmount"] integerValue] &&
                    [_freightAreaSelected isEqual:_originalData[@"areaFreightList"]]) {

                    [self.navigationController popViewControllerAnimated:YES];
                }
                else {
                    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_110") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
                    [alertView show];
                }

            }
            else {
                [self.navigationController popViewControllerAnimated:YES];
            }
            
//            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_110") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
            [alertView show];
        }
        
    }
}

- (void)saveButtonEvent:(id)sender
{

    JSONRequest* request;
    
    //id为0，表示新增模板
    if (_templateId == 0) {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_FREIGHT_TEMPLATE_ADD];
    }
    
    //id不为0，表示修改模板
    else {
        request = [[JSONRequest alloc] initWithURLString:_JSON_URL_FREIGHT_TEMPLATE_CHANGE_INFO];
        [request setValue:[NSNumber numberWithInteger:_templateId] forParameter:@"id"];
    }
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    
    //获取姓名
    NSString *name = [_webView stringByEvaluatingJavaScriptFromString:@"template_name.value"];
    
    //谁包邮
    //0买家承担运费，1.卖家承担运费；
    NSInteger type;
    
    //买家承担运费，就要向服务器传递以下的参数
    if ([[_webView stringByEvaluatingJavaScriptFromString:@"check_freight_method();"] boolValue]) {
        type = 0;
    
        //默认数量
        NSString *defaultQuantity = [_webView stringByEvaluatingJavaScriptFromString:@"default_quantity.value"];
        
        //默认金额
        NSString *defaultAmount = [_webView stringByEvaluatingJavaScriptFromString:@"default_amount.value"];
        
        //超出数量
        NSString *exceedQuantity = [_webView stringByEvaluatingJavaScriptFromString:@"exceed_quantity.value"];
        
        //超出金额
        NSString *exceedAmount = [_webView stringByEvaluatingJavaScriptFromString:@"exceed_amount.value"];
        
        //区域列表
        NSString *json;
        
        if ([NSJSONSerialization isValidJSONObject:_freightAreaSelected] && _freightAreaSelected != nil && _freightAreaSelected.count != 0)
        {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_freightAreaSelected options:NSJSONWritingPrettyPrinted error:&error];
            json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"json data:%@",json);
        }
        
        [request setValue:defaultQuantity forParameter:@"defaultQuantity"];
        [request setValue:defaultAmount forParameter:@"defaultAmount"];
        [request setValue:exceedQuantity forParameter:@"exceedQuantity"];
        [request setValue:exceedAmount forParameter:@"exceedAmount"];
        [request setValue:json forParameter:@"areaFreightList"];
    }
    
    //买家承担运费，只需要传递类型
    else {
        
        type = 1;
    }
    
    //调用JS的tester方法，返回假就说明有字段没有被认证通过
    NSString* tester = [_webView stringByEvaluatingJavaScriptFromString:@"tester();"];
    BOOL result = [tester boolValue];
    
    //有没有通过认证的字段，就什么都不做
    if (result == false) {
        
        return;
    }
    
    //发货地址id
    if (_sendReceivingId == 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"holder_38")];
        return;
    }
    
    //退货地址id
    if (_returnReceivingId == 0) {
        [Helper showAlertWithTitle:@"" andMessage:_L(@"holder_39")];
        return;
    }
    
    //判断是否继续保存此物流模板
    //由于区域运费是可选的，但还是有必要在用户在选择买家承担运费且没有设置区域运费的时候提醒用户。
    //变量_templateContinueSaving，主要用来控制这个是否再次检验这个区域运费这个逻辑
    //在alertview的代理方法里面有体现，当用户点击提醒框的“继续保存”，则表明用户确认不用添加区域运费，否则继续检测用户是否选择区域运费。
    if (_templateContinueSaving && type == 0) {
        
        if (_freightAreaSelected == nil || _freightAreaSelected.count == 0) {
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_114") delegate:self cancelButtonTitle:_L(@"btn_yes_38") otherButtonTitles:_L(@"btn_yes_39"), nil];
            alertView.tag = 2;
            [alertView show];
            return;
        }
    }
    
    [request setValue:name forParameter:@"name"];
    [request setValue:[NSNumber numberWithInteger:type] forParameter:@"type"];
    [request setValue:_currentUnit forParameter:@"unitName"];
    [request setValue:[NSNumber numberWithInteger:_sendReceivingId] forParameter:@"sendReceivingId"];
    [request setValue:[NSNumber numberWithInteger:_returnReceivingId] forParameter:@"returnReceivingId"];
    [request setSuccessSelector:@selector(freightTemplateDidAdded:)];
    
    [request asynchronous];
}

#pragma mark - 私有方法

//查看运费模板详情
- (void)loadFreightTemplateData
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_FREIGHT_TEMPLATE_DETAILINFO];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    
    [request setValue:[NSNumber numberWithInteger:_templateId] forParameter:@"freightId"];
    [request asynchronous];
}

//设置运费列表
//没添加一个区域运费就执行一次此方法，显示在HTML上。
- (void)freightListWithFreight:(NSDictionary *)freight andIndex:(NSInteger)index
{
    //拼接省市字符串
    NSString *provinces = @"";
    
    //城市总个数
    NSInteger cityNum = 0;
    
    if ([freight[@"areaFreightRegionList"] count] > 0 && [freight[@"areaFreightRegionList"] count] < 6) {
        //如果被选中的省市没有超过5个
        for (int i=0; i<[freight[@"areaFreightRegionList"] count]; i++) {
            
            provinces = [provinces stringByAppendingString:freight[@"areaFreightRegionList"][i][@"province"]];
            if (i != [freight[@"areaFreightRegionList"] count]-1) {
                provinces = [provinces stringByAppendingString:@","];
            }
        }
        
        
    }
    else {
        //如果被选中的省市超过5个
        for (int i=0; i<5; i++) {
            
            provinces = [provinces stringByAppendingString:freight[@"areaFreightRegionList"][i][@"province"]];
            if (i != 4) {
                provinces = [provinces stringByAppendingString:@","];
            }
        }

    }

//    for (int i=0; i<[freight[@"areaFreightRegionList"] count]; i++) {
//    
//        cityNum += [freight[@"areaFreightRegionList"][i][@"cityNum"] integerValue];
//    
//    }

    cityNum = [freight[@"areaFreightRegionList"] count];
    
    NSInteger defaultQuantity = [freight[@"defaultQuantity"] integerValue];
    NSInteger defaultAmount = [freight[@"defaultAmount"] integerValue];
    NSInteger exceedQuantity = [freight[@"exceedQuantity"] integerValue];
    NSInteger exceedAmount = [freight[@"exceedAmount"] integerValue];
    
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"freightList(%d,'%@',%d,%d,%d,%d,%d);", index, provinces, cityNum,defaultQuantity,defaultAmount,exceedQuantity,exceedAmount]];
}

//显示区域运费列表
- (void)showFreightList
{
    if (_freightAreaSelected.count != 0) {
        
        //先将列表清空
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"area_freight_list.innerHTML='%@';", @""]];
        
        //显示出区域运费列表
        for (int i=0; i<_freightAreaSelected.count; i++) {
            
            [self freightListWithFreight:_freightAreaSelected[i] andIndex:i];
        }
        
    }
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{

    //新建
    if (_templateId == 0) {
        
        //设置发货地址和退货地址默认title
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_delivery_title.innerHTML='%@';", _L(@"holder_38")]];
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_return_title.innerHTML='%@';", _L(@"holder_39")]];
        
        //新建，就不存在设置默认和删除
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"default\").style.display = 'none';"];
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"delete_button\").style.display = 'none';"];
    }
    
    //修改
    else{
        
        _templateContinueSaving = NO;
        
        //设置发货地址和退货地址默认title
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_delivery_title.innerHTML='%@';", _L(@"holder_40")]];
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_return_title.innerHTML='%@';", _L(@"holder_41")]];
        
        //显示出删除按钮
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"delete_button\").style.display = 'block';"];
        
        //请求此模板详情
        [self loadFreightTemplateData];
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    if (_noAlert) {
        return true;
    }
    
    NSArray *strArray = [[request.URL.relativeString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]componentsSeparatedByString:@"?"];
    
    //选择区域
    if ([strArray[0] isEqualToString:@"open:area_selectVC"]) {

        FreightAreaViewController *freightAreaVC = [[FreightAreaViewController alloc] init];
        freightAreaVC.delegate = self;

        //新建区域的时候
        if (strArray.count == 1) {
            UINavigationController* freightAreaNC = [[UINavigationController alloc] initWithRootViewController:freightAreaVC];
            
            [Helper navigationControllerCommonStyle:freightAreaNC];
            
            [self.navigationController presentModalViewController:freightAreaNC animated:true];
        }
        
        //查看详情，第二个参数为区域运费列表的索引
        if (strArray.count == 2) {
            _currentFreightIndex = [strArray[1] integerValue];
            
            freightAreaVC.areaInfo = _freightAreaSelected[_currentFreightIndex];
            
            [self.navigationController pushViewController:freightAreaVC animated:YES];
        }
    }
    
    //选择发货地址
    else if ([strArray[0] isEqualToString:@"open:delivery_address"]) {
        
        _currentAddrPicker = YES;
        
        AddressPickerViewController *addressPickerViewVC= [[AddressPickerViewController alloc] init];
        addressPickerViewVC.delegate = self;
        if (_sendReceivingId != 0) {
            addressPickerViewVC.selectedAddrId = _sendReceivingId;
        }
        [self.navigationController pushViewController:addressPickerViewVC animated:YES];
    }
    
    //选择退货地址
    else if ([strArray[0] isEqualToString:@"open:return_address"]) {
        
        _currentAddrPicker = NO;
        
        AddressPickerViewController *addressPickerViewVC= [[AddressPickerViewController alloc] init];
        addressPickerViewVC.delegate = self;
        if (_returnReceivingId != 0) {
            addressPickerViewVC.selectedAddrId = _returnReceivingId;
        }
        [self.navigationController pushViewController:addressPickerViewVC animated:YES];
    }
    
    //设置默认模板
    else if ([strArray[0] isEqualToString:@"set:default"]) {

        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_FREIGHT_TEMPLATE_CHANGE_DEFAULT];
        [request setValue:[NSNumber numberWithInteger:_templateId]  forParameter:@"freightId"];
        NSDictionary* dict = [request synchronous];
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
        if (jmf.status == JMStatusSucceed) {
            if (_templateId == 0) {
                [self.navigationController dismissModalViewControllerAnimated:true];
            }
            else {
                [self.navigationController popViewControllerAnimated:true];
            }
        }
        else {
            [Helper easyShowJMFStatus:jmf];
        }
    }
    
    //删除模板
    else if ([strArray[0] isEqualToString:@"delete:template"]) {
        
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:_L(@"alert_117") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];   //确定是否要删除此地址
        alerView.tag = 3;
        [alerView show];
        
    }
    
    //警告框
    else if ([strArray[0] isEqualToString:@"open:alert"]) {
        
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"" message:strArray[1] delegate:self cancelButtonTitle:_L(@"btn_yes_01") otherButtonTitles:nil];
        alerView.tag = 100;
        [alerView show];
    }


    return true;
}

#pragma mark - AddressPickerViewControllerDelegate

- (void)addressPicked:(NSDictionary *)consignee
{
    if (_currentAddrPicker) {
        
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_delivery_title.innerHTML='%@';", _L(@"holder_40")]];
        _sendReceivingId = [consignee[@"id"] integerValue];

        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_delivery.innerHTML='%@ %@';", consignee[@"region"],consignee[@"address"]]];
    }
    else {
        
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_return_title.innerHTML='%@';", _L(@"holder_41")]];
        _returnReceivingId = [consignee[@"id"] integerValue];

        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_return.innerHTML='%@ %@';", consignee[@"region"],consignee[@"address"]]];
    }
}

#pragma mark - FreightAreaSelectedDelegate

- (void)freightAreaDidSelected:(NSDictionary *)area withType:(NSInteger)type
{
    //type为0表示新建的区域，type为1便是更改的
    if (type == 0) {
        [_freightAreaSelected addObject:[NSDictionary dictionaryWithDictionary:area]];
    }
    else if (type == 1){
        [_freightAreaSelected replaceObjectAtIndex:_currentFreightIndex withObject:area];
    }
    
    [self showFreightList];
}

- (void)freightWillDelete
{
    [_freightAreaSelected removeObjectAtIndex:_currentFreightIndex];
    
    [self showFreightList];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        _originalData = jmf.data;
        
        //渲染页面
        
        //模板名称
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"template_name.value='%@';", jmf.data[@"name"]]];
        
        //谁包邮
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"checkboxesValue('%d');", [jmf.data[@"type"] integerValue]]];
        
        //买家包邮,就渲染运费，区域运费这些，否则不渲染
        if (![jmf.data[@"type"] integerValue]) {
            
            [_freightAreaSelected addObjectsFromArray:jmf.data[@"areaFreightList"]];
            
            [self showFreightList];
            
            //默认数量
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"default_quantity.value=%@",jmf.data[@"defaultQuantity"]]];
            
            //默认金额
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"default_amount.value=%@",jmf.data[@"defaultAmount"]]];
            
            //超出数量
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"exceed_quantity.value=%@",jmf.data[@"exceedQuantity"]]];
            
            //超出金额
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"exceed_amount.value=%@",jmf.data[@"exceedAmount"]]];
        }
        
        //卖家包邮,什么也不做
        else {
            
        }
        
        //发货地址
        _sendReceivingId = [jmf.data[@"sendReceivingId"] integerValue];
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_delivery.innerHTML='%@';", jmf.data[@"sendAddress"]]];
      
        //退货地址
        _returnReceivingId = [jmf.data[@"returnReceivingId"] integerValue];
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"address_return.innerHTML='%@';", jmf.data[@"returnAddress"]]];

        //0为普通模版，1为默认模版
        //为0时，要显示设为默认模板的按钮
        if ([jmf.data[@"status"] integerValue]) {
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"default\").style.display = 'none';"];
        }
        else {
            [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"default\").style.display = 'block';"];
        }
        
        //当卖家承担运费时，运费相关就不用显示
        [_webView stringByEvaluatingJavaScriptFromString:@"check_freight_method();"];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//运费模板被添加
- (void)freightTemplateDidAdded:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {

        if (_templateId == 0) {
            [self.navigationController dismissModalViewControllerAnimated:YES];
        }
        else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
        _templateContinueSaving = YES;
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
    _templateContinueSaving = YES;
}

#pragma mark - UIAlerView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 2) {
        
        //确认完成
        if (buttonIndex == 0) {
            _templateContinueSaving = NO;
            
            [self saveButtonEvent:nil];
        }
        
        //返回设置
        else if (buttonIndex == 1) {
            _templateContinueSaving = YES;
            
        }
        
    }
    else if (alertView.tag == 3) {
        
        if (buttonIndex == 1) {
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_FREIGHT_TEMPLATE_REMOVE];
            
            [request setValue:[NSNumber numberWithInteger:_templateId] forParameter:@"freightId"];
            
            JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:[request synchronous]];
            
            if (jmf.status == 1) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }

            [Helper easyShowJMFStatus:jmf];
        }
    }

    else {
        if (buttonIndex == 1) {
            
            //要退出时，设定不在接受HTML的Alert
            _noAlert = true;
            
            if (_templateId == 0) {
                [self.navigationController dismissModalViewControllerAnimated:YES];
            }
            else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
    }
}


@end
